<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div class="head_img pr">
      <em class="pa"></em>
      <img src='' alt="" class="modify_img" />
      <input id="photo" type="file" accept="image/*" />
      <input id="photo2" type="file" accept="image/*" />
      <input id="photo3" type="file" accept="image/*" />
  </div>
  <script src="../js/jquery-1.12.4.js" charset="utf-8"></script>
<script type="text/javascript">
$('input[type="file"]').change(function(){
      var _this = $(this)[0],
          _file = _this.files[0],
          fileType = _file.type;
          console.log(_file.size,_file);
      if(/image\/\w+/.test(fileType)){
          console.log('图片上传中...');
          imgCutDown(_file,function(dataURL, blob){
              console.log("ok")
                $('.modify_img').attr('src',dataURL);
          })
      }else{
          $.notify.show('请选择图片格式文件', {placement: 'center'});
      }
  });

  var imgCutDown = function(_file,callback){
    var fileReader = new FileReader();
    fileReader.readAsDataURL(_file);
    fileReader.onload = function(event){
      var result = event.target.result;   //返回的dataURL result
      var sizeMax = 500;                  // 缩小的图片
      var image = new Image();
      image.src = result;
      image.onload = function(){
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        var  width = this.width,
             height = this.height;
        var scale = 1; //从第一倍开始压缩
    		console.log('开始图片压缩...');
        for (;;) {
    			canvas.width = width / scale;
    			canvas.height = height / scale;
    			ctx.drawImage(this, 0, 0, width / scale, height / scale);
    			var _dataURL = canvas.toDataURL( _file.type);
    			var	blob = dataURLtoBlob(_dataURL);
    			size = blob.size / 1024;
    			if (size < sizeMax) { //指定之下
    				console.log('是真——第' + scale + '倍压缩完成=>', Math.floor(size) + 'kb');
            if (callback && $.isFunction(callback)) {
              callback(_dataURL, blob);
            }
    				break;
    			} else { //继续压缩
    				console.log('这是假——第' + scale + '倍的压缩', Math.floor(size) + 'kb');
    				scale++;
    			}
        }
  		}
    }
  }

var dataURLtoBlob = function(dataurl) {//dataURL->blob
  var arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], {
    type: mime
  });
}
</script>
</body>
</html>
